package com.lark.view.splash;

import com.lark.utils.ResourcesUtil;
import com.lark.view.SplashScreen;
import javafx.animation.Interpolator;
import javafx.animation.RotateTransition;
import javafx.animation.Timeline;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.shape.Arc;
import javafx.util.Duration;

import static javafx.scene.layout.Region.USE_PREF_SIZE;

/**
 * 启动动画界面
 */
public class LoadingScreen extends SplashScreen {

    private static final String STYLE_SHEET = ResourcesUtil.convertFilePath("static/css/loading.css");

    private final double size = 50d;

    private Arc frontArc;
    // 布局
    private final Pane arcPane = new Pane();
    private final RotateTransition RT = new RotateTransition();

    public LoadingScreen() {
        super(true);
    }

    public LoadingScreen(boolean visible) {
        super(visible);
    }

    @Override
    public Parent getParent() {
        // 加载圈
        Arc backArc = getArc(360);
        this.frontArc = getArc(90);
        backArc.getStyleClass().add("back-arc");
        this.frontArc.getStyleClass().add("front-arc");

        this.arcPane.getChildren().addAll(backArc, frontArc);
        this.arcPane.setPrefSize(this.size, this.size);
        this.arcPane.setMaxSize(USE_PREF_SIZE, USE_PREF_SIZE);
        Label message = new Label("Loading...");
        message.getStyleClass().add("message");

        final VBox vbox = new VBox() {
            @Override
            public String getUserAgentStylesheet() {
                return STYLE_SHEET;
            }
        };
        vbox.setSpacing(10);
        vbox.setPadding(new Insets(10));
        vbox.getChildren().addAll(arcPane, message);
        vbox.setAlignment(Pos.CENTER);
        vbox.setStyle("-fx-background-color: null");

        // 动画
        setAnimation();
        return vbox;
    }

    private Arc getArc(double arcLength) {
        double size = this.size / 2;
        Arc arc = new Arc(size, size, size, size, 0, arcLength);
        arc.setFill(null);
        double strokeWidth = 3d;
        arc.setStrokeWidth(strokeWidth);
        return arc;
    }

    @Override
    public void setAnimation() {
        Button TRANSITION_NODE = new Button();
        frontArc.startAngleProperty().bind(TRANSITION_NODE.rotateProperty());
        //旋转动画
        RT.setNode(TRANSITION_NODE);
        RT.setFromAngle(360);
        RT.setToAngle(0);
        RT.setDuration(Duration.millis(1000));
        RT.setInterpolator(Interpolator.LINEAR);
        RT.setCycleCount(Timeline.INDEFINITE);
        RT.play();
    }

    @Override
    public boolean visible() {
        return visible;
    }

    @Override
    public void stop() {
        RT.stop();
    }
}
